
const fs = require('fs')
const common = require('./common')
const path = require('path')
const url = require('url')
const ejs = require('ejs')

const static = function(req, res, staticPath) {
  // 1. 获取地址
  let pathname = url.parse(req.url).pathname; // 去掉 search后缀

  pathname = pathname === '/' ? '/index.html':pathname

  // 可以获取后缀名 path.extname()
  let extname = path.extname(pathname)

  // 2. 通过fs模块读取文件
  if(pathname !== '/favicon.ico') {
    try {
      let data = fs.readFileSync('./' + staticPath + pathname)
      if(data) {
        let mime = common.getFileMimeSync(extname)
        res.writeHead(200, {'Content-Type': mime +';charset=utf-8'})
        res.end(data)
      }
    } catch (error) {
      
    }
  }
}
exports.static = static

let app = {
  static: (req, res, staticPath) => {
    // 处理登录的业务逻辑
    static(req, res, staticPath)
  },
  login: (req, res) => {
    // 处理登录的业务逻辑
    ejs.renderFile('./views/form.ejs', {}, (err, data) =>{
      res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
      res.end(data)
    })
  },
  register: (req, res) => {
    res.end('reaister')
  },
  news: (req, res) => {
    res.end('news')
  },
  doLogin: (req, res) => {
    var postData = ''
    req.on('data', (chunk) => {
      postData += chunk
    })

    req.on('end', (err) => {
      console.log(postData)
      res.end(postData)
    })
  },
  error: (req, res) => {
    res.end('error')
  }
}

module.exports = app